#include "board_spi.h"
#include "board_config.h"

SPI_HandleTypeDef spi1handler;

GPIO_TypeDef* SPI_PERIPH_PORT[SPI_PERIPH_NUM] = {
	ADIS16405_SPI_CS_GPIO_PORT
};

const uint16_t SPI_PERIPH_CS_PIN[SPI_PERIPH_NUM] = {
	ADIS16405_SPI_CS_PIN
};

void board_spi_init(SPI_HandleTypeDef *spihandler)
{
	if (spihandler == &spi1handler) {
		spihandler->Instance 			= BOARD_SPI1;
		spihandler->Init.BaudRatePrescaler 	= SPI_BAUDRATEPRESCALER_128;
		spihandler->Init.Direction 		= SPI_DIRECTION_2LINES;
		spihandler->Init.CLKPhase          	= SPI_PHASE_2EDGE;
		spihandler->Init.CLKPolarity       	= SPI_POLARITY_HIGH;
		spihandler->Init.CRCCalculation    	= SPI_CRCCALCULATION_DISABLE;
		spihandler->Init.CRCPolynomial     	= 7;
		spihandler->Init.DataSize          	= SPI_DATASIZE_8BIT;
		spihandler->Init.FirstBit          	= SPI_FIRSTBIT_MSB;
		spihandler->Init.NSS               	= SPI_NSS_SOFT;
		spihandler->Init.TIMode            	= SPI_TIMODE_DISABLE;
		spihandler->Init.Mode			= SPI_MODE_MASTER;
	}
	HAL_SPI_Init(spihandler);
}

/**
 * @brief SPI MSP Initialization 
 *        This function configures the hardware resources used in this example: 
 *           - Peripheral's clock enable
 *           - Peripheral's GPIO Configuration  
 *           - DMA configuration for transmission request by peripheral 
 *           - NVIC configuration for DMA interrupt request enable
 * @param hspi: SPI handle pointer
 * @retval None
 */
void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi)
{
	static DMA_HandleTypeDef hdma_tx;
	static DMA_HandleTypeDef hdma_rx;

	GPIO_InitTypeDef  GPIO_InitStruct;

	if (hspi == &spi1handler) {
		/*##-1- Enable peripherals and GPIO Clocks #################################*/
		/* Enable GPIO TX/RX clock */
		BOARD_SPI1_SCK_GPIO_CLK_ENABLE();
		BOARD_SPI1_MISO_GPIO_CLK_ENABLE();
		BOARD_SPI1_MOSI_GPIO_CLK_ENABLE();
		/* Enable SPI clock */
		BOARD_SPI1_CLK_ENABLE(); 
		/* Enable DMA1 clock */
		BOARD_SPI1_DMA_CLK_ENABLE();   

		/* Enable devices' cs pin clock */
		ADIS16405_SPI_CS_GPIO_CLK_ENABLE();

		/*##-2- Configure peripheral GPIO ##########################################*/  
		/* SPI SCK GPIO pin configuration  */
		GPIO_InitStruct.Pin       = BOARD_SPI1_SCK_PIN;
		GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
		GPIO_InitStruct.Pull      = GPIO_PULLUP;
		GPIO_InitStruct.Speed     = GPIO_SPEED_FAST;
		GPIO_InitStruct.Alternate = BOARD_SPI1_AF;
		HAL_GPIO_Init(BOARD_SPI1_SCK_GPIO_PORT, &GPIO_InitStruct);

		/* SPI MISO GPIO pin configuration  */
		GPIO_InitStruct.Pin = BOARD_SPI1_MISO_PIN;
		HAL_GPIO_Init(BOARD_SPI1_MISO_GPIO_PORT, &GPIO_InitStruct);

		/* SPI MOSI GPIO pin configuration  */
		GPIO_InitStruct.Pin = BOARD_SPI1_MOSI_PIN;
		HAL_GPIO_Init(BOARD_SPI1_MOSI_GPIO_PORT, &GPIO_InitStruct);

		/* devices' cs pin configuration */
		GPIO_InitStruct.Pin = ADIS16405_SPI_CS_PIN;
		GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
		HAL_GPIO_Init(ADIS16405_SPI_CS_GPIO_PORT, &GPIO_InitStruct);

		HAL_GPIO_WritePin(ADIS16405_SPI_CS_GPIO_PORT, ADIS16405_SPI_CS_PIN, GPIO_PIN_SET);

		/*##-3- Configure the DMA streams ##########################################*/
		/* Configure the DMA handler for Transmission process */
		hdma_tx.Instance                 = BOARD_SPI1_TX_DMA_STREAM;

		hdma_tx.Init.Channel             = BOARD_SPI1_TX_DMA_CHANNEL;
		hdma_tx.Init.Direction           = DMA_MEMORY_TO_PERIPH;
		hdma_tx.Init.PeriphInc           = DMA_PINC_DISABLE;
		hdma_tx.Init.MemInc              = DMA_MINC_ENABLE;
		hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
		hdma_tx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
		hdma_tx.Init.Mode                = DMA_NORMAL;
		hdma_tx.Init.Priority            = DMA_PRIORITY_LOW;
		hdma_tx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;         
		hdma_tx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
		hdma_tx.Init.MemBurst            = DMA_MBURST_INC4;
		hdma_tx.Init.PeriphBurst         = DMA_PBURST_INC4;

		HAL_DMA_Init(&hdma_tx);   

		/* Associate the initialized DMA handle to the the SPI handle */
		__HAL_LINKDMA(hspi, hdmatx, hdma_tx);

		/* Configure the DMA handler for Transmission process */
		hdma_rx.Instance                 = BOARD_SPI1_RX_DMA_STREAM;

		hdma_rx.Init.Channel             = BOARD_SPI1_RX_DMA_CHANNEL;
		hdma_rx.Init.Direction           = DMA_PERIPH_TO_MEMORY;
		hdma_rx.Init.PeriphInc           = DMA_PINC_DISABLE;
		hdma_rx.Init.MemInc              = DMA_MINC_ENABLE;
		hdma_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
		hdma_rx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
		hdma_rx.Init.Mode                = DMA_NORMAL;
		hdma_rx.Init.Priority            = DMA_PRIORITY_HIGH;
		hdma_rx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;         
		hdma_rx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
		hdma_rx.Init.MemBurst            = DMA_MBURST_INC4;
		hdma_rx.Init.PeriphBurst         = DMA_PBURST_INC4; 

		HAL_DMA_Init(&hdma_rx);

		/* Associate the initialized DMA handle to the the SPI handle */
		__HAL_LINKDMA(hspi, hdmarx, hdma_rx);

		/*##-4- Configure the NVIC for DMA #########################################*/ 
		/* NVIC configuration for DMA transfer complete interrupt (SPI1_TX) */
		HAL_NVIC_SetPriority(BOARD_SPI1_DMA_TX_IRQn, 0, 1);
		HAL_NVIC_EnableIRQ(BOARD_SPI1_DMA_TX_IRQn);

		/* NVIC configuration for DMA transfer complete interrupt (SPI3_RX) */
		HAL_NVIC_SetPriority(BOARD_SPI1_DMA_RX_IRQn, 0, 0);   
		HAL_NVIC_EnableIRQ(BOARD_SPI1_DMA_RX_IRQn);
	}
}

/**
 * @brief SPI MSP De-Initialization 
 *        This function frees the hardware resources used in this example:
 *          - Disable the Peripheral's clock
 *          - Revert GPIO, DMA and NVIC configuration to their default state
 * @param hspi: SPI handle pointer
 * @retval None
 */
void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi)
{
	static DMA_HandleTypeDef hdma_tx;
	static DMA_HandleTypeDef hdma_rx;

	__HAL_LINKDMA(hspi, hdmatx, hdma_tx);
	__HAL_LINKDMA(hspi, hdmarx, hdma_rx);

	if (hspi == &spi1handler) {
		/*##-1- Reset peripherals ##################################################*/
		BOARD_SPI1_FORCE_RESET();
		BOARD_SPI1_RELEASE_RESET();

		/*##-2- Disable peripherals and GPIO Clocks ################################*/
		/* Configure SPI SCK as alternate function  */
		HAL_GPIO_DeInit(BOARD_SPI1_SCK_GPIO_PORT, BOARD_SPI1_SCK_PIN);
		/* Configure SPI MISO as alternate function  */
		HAL_GPIO_DeInit(BOARD_SPI1_MISO_GPIO_PORT, BOARD_SPI1_MISO_PIN);
		/* Configure SPI MOSI as alternate function  */
		HAL_GPIO_DeInit(BOARD_SPI1_MOSI_GPIO_PORT, BOARD_SPI1_MOSI_PIN);

		/*##-3- Disable the DMA Streams ############################################*/
		/* De-Initialize the DMA Stream associate to transmission process */
		HAL_DMA_DeInit(&hdma_tx); 
		/* De-Initialize the DMA Stream associate to reception process */
		HAL_DMA_DeInit(&hdma_rx);

		/*##-4- Disable the NVIC for DMA ###########################################*/
		HAL_NVIC_DisableIRQ(BOARD_SPI1_DMA_TX_IRQn);
		HAL_NVIC_DisableIRQ(BOARD_SPI1_DMA_RX_IRQn);
	}
}

void spi_select(spi_periph dev, uint8_t state)
{
	if (state == 0) {
		HAL_GPIO_WritePin(SPI_PERIPH_PORT[dev], SPI_PERIPH_CS_PIN[dev], GPIO_PIN_SET);
		return;
	}
	HAL_GPIO_WritePin(SPI_PERIPH_PORT[dev], SPI_PERIPH_CS_PIN[dev], GPIO_PIN_RESET);
}

